package com.example.sp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);
    }

    //保存到SP
    public void saveToSP(View view) {
        SharedPreferences sp = getSharedPreferences("sp", Context.MODE_PRIVATE);
        sp.edit().putString("Name", "星辰").apply();
        sp.edit().putInt("Age", 19).apply();
        Toast.makeText(this, "已保存到SP", Toast.LENGTH_SHORT).show();
    }

    //获取SP的数据
    public void getSP(View view) {
        SharedPreferences sp = getSharedPreferences("sp", Context.MODE_PRIVATE);
        String value = sp.getString("Name", "默认值");
        int value2 = sp.getInt("Age", 19);
        tv.setTextSize(30);
        tv.setText(value + "   " + String.valueOf(value2) + "岁");
//        tv.setText(String.valueOf(value2));
    }
}